package com.tarena.ELSFK.day02_all.ext;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Demo05 {
	public static void main(String[] args) {
		JFrame frame = new JFrame();
		MyPanel panel = new MyPanel();
		frame.add(panel);
		frame.setSize(25*10, 25*20);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
		panel.action();
	}
}
class MyPanel extends JPanel{
	Tetromino t;//父类型变量 t，可以引用任何的子类型实例
	public void action(){
		//t 可以应用 I 或者 T 对象!
		t = new T();// t = new T();
		repaint();
		KeyAdapter l = new KeyAdapter() {
			public void keyPressed(KeyEvent e) {
				int key = e.getKeyCode();
				switch(key){
				case KeyEvent.VK_RIGHT: t.moveRight(); break;
				case KeyEvent.VK_LEFT: t.moveLeft(); break;
				case KeyEvent.VK_DOWN: t.moveDown(); break;
				}
				repaint();
			}
		};
		this.requestFocus();
		this.addKeyListener(l);
	}
	
	public void paint(Graphics g) {
		g.setColor(new Color(0xdddddd));
		g.fillRect(0, 0, 25*10, 25*20);
		Cell[] cells = t.cells;
		for(int i=0; i<cells.length; i++){
			Cell c = cells[i];
			g.setColor(new Color(c.color));
			int x = c.col * 25;
			int y = c.row * 25;
			g.fillRect(x, y, 25, 25);
		}
	}
}
class Cell{
	int row;
	int col;
	int color;
	public Cell(int row, int col, int color) {
		this.row = row;
		this.col = col;
		this.color = color;
	}
	public void moveRight(){ col++; }
	public void moveLeft(){	col--; }
	public void moveDown(){	row++; }
}
// 继承语法 Tetromino 是父类型(Super class)，T,I 是子类型
// sub class 子类型 继承父类型的属性和方法
/** Tetromino 4格方块，俄罗斯方块游戏专用词！ */
class Tetromino{
	Cell[] cells;
	public void moveRight(){
		for(int i=0; i<cells.length; i++){
			cells[i].moveRight();
		}
	}
	public void moveLeft(){
		for(int i=0; i<cells.length; i++){
			cells[i].moveLeft();
		}
	}
	public void moveDown(){
		for(int i=0; i<cells.length; i++){
			cells[i].moveDown();
		}
	}
}
/** 子类T继承了父类的属性(cells)和方法(moveDown()...) */
class T extends Tetromino{
	public T() {
		cells = new Cell[4];
		cells[0] = new Cell(0, 4, 0xff0000);
		cells[1] = new Cell(0, 3, 0xff0000);
		cells[2] = new Cell(0, 5, 0xff0000);
		cells[3] = new Cell(1, 4, 0xff0000);
	}
}
class I extends Tetromino{
	public I() {
		cells = new Cell[4];
		cells[0] = new Cell(0, 4, 0xffff00);
		cells[1] = new Cell(0, 3, 0xffff00);
		cells[2] = new Cell(0, 5, 0xffff00);
		cells[3] = new Cell(0, 6, 0xffff00);
	}
}
